package com.sz.biz.logistics.ord.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.logistics.constants.BaseConstants;
import com.sz.biz.logistics.constants.OrderConstants;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.EntityUtils;
import com.sz.biz.logistics.ord.entity.OrdOrderStatusCode;
import com.sz.biz.logistics.ord.service.OrdOrderStatusCodeService;
import com.sz.biz.logistics.ord.dto.OrdOrderStatusCodeDto;
import com.sz.biz.logistics.ord.dto.OrderStatusCodeDto;
import com.sz.biz.logistics.ord.dto.TrackStatusOperTypeDto;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.entity.SysDict;
import com.sz.common.core.system.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Package: com.sz.biz.logistics.ord.service.impl <br>
 * Function: 物流状态等级映射关系表service <br>
 * Author: hpeng.wang. <br>
 * Date: 2017-04-28 10:09:00.
 */
@Service
public class OrdOrderStatusCodeServiceImpl extends AbstractService implements OrdOrderStatusCodeService {
    private static final String REGEX = "\\[..\\]";
    @Autowired
    private SysDictService sysDictService;

    @Override
    protected String getMapperNamespace() {
        return "com.sz.biz.logistics.ord.entity.OrdOrderStatusCodeMapper";
    }

    @Override
    public List<String> findReviseStatusList() {
        List<String> codeList = dao.findForList(getSqlName("findReviseStatusList"), null, String.class);
        return codeList;
    }

    @Override
    public List<OrdOrderStatusCode> findReviseStatus() {
        List<OrdOrderStatusCode> codeList = dao.findForList(getSqlName("findReviseStatus"), null, OrdOrderStatusCode.class);
        return codeList;
    }

    @Override
    public OrdOrderStatusCode getByCode(String code) {
        ParamData pd = new ParamData();
        pd.put("code", code);
        OrdOrderStatusCode statusCode = (OrdOrderStatusCode) dao.findForObject(getSqlName("getByCode"), pd);
        return statusCode;
    }

    @Override
    public List<OrdOrderStatusCodeDto> getAllCodes() {
        List<OrdOrderStatusCode> list = dao.findForList(getSqlName("getAllCodes"), null, OrdOrderStatusCode.class);
        List<OrdOrderStatusCodeDto> resultLit = Lists.newArrayList();
        if (null != list && !list.isEmpty()) {
            for (OrdOrderStatusCode statusCode : list
                    ) {

                OrdOrderStatusCodeDto dto = new OrdOrderStatusCodeDto();
                EntityUtils.copyPropertiesIgnoreNull(statusCode, dto);
                //处理
                // 1= 客户，2=运营， 3=销售，管理
                if (statusCode.getRank() == OrderConstants.OrderTrackRank.TRACKING_CUSTOMER) {
                    dto.setRankPermission(OrderConstants.OrderTrackRank.TRACKING_CUSTOMER_NAME);
                }
                if (statusCode.getRank() == OrderConstants.OrderTrackRank.TRACKING_CUSTOMER_SERVICE) {
                    dto.setRankPermission(OrderConstants.OrderTrackRank.TRACKING_CUSTOMER_SERVICE_NAME);
                }
                if (statusCode.getRank() == OrderConstants.OrderTrackRank.TRACKING_MANAGER) {
                    dto.setRankPermission(OrderConstants.OrderTrackRank.TRACKING_MANAGER_NAME);
                }
                if (null != statusCode.getOrderStatus()) {
                    dto.setOrderStatusName(statusCode.getOrderStatus().getName());
                }
                resultLit.add(dto);
            }

        }
        return resultLit;
    }

    @Override
    public List<OrderStatusCodeDto> getCodesByType(List<Integer> rankList, int type) {
        if ((type != OrderConstants.OrderTrackRank.TRACKING_CUSTOMER && type != OrderConstants.OrderTrackRank.TRACKING_CUSTOMER_SERVICE) || CollectionUtils.isEmpty(rankList)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "参数异常");
        }
        ParamData pd = new ParamData();
        pd.put("type", type);
        pd.put("ranks", rankList);
        List<OrdOrderStatusCode> orderStautsCodeList = dao.findForList(getSqlName("getCodesByType"), pd, OrdOrderStatusCode.class);
        if (!CollectionUtils.isEmpty(orderStautsCodeList)) {
            List<OrderStatusCodeDto> dtos = Lists.newArrayList();
            orderStautsCodeList.forEach(statusCode -> {
                OrderStatusCodeDto dto = new OrderStatusCodeDto();
                dto.setCode(statusCode.getCode());
                String messageTemplate = statusCode.getMessageTemplate();
                //设置解析参数
                List<String> paramList = EntityUtils.extractMessageByRegular(messageTemplate, CommCodes.ORD_TRACKING_REGEX);
                dto.setParams(paramList);
                dto.setMessageTemplate(messageTemplate);
                dtos.add(dto);
            });
            return dtos;
        }
        return null;
    }
    @Override
    public List<TrackStatusOperTypeDto> getCodesByType(List<Integer> rankList) {
        List<TrackStatusOperTypeDto> operTypeDtoList = Lists.newArrayList();

        ParamData pd = new ParamData();
        pd.put("ranks", rankList);
        List<OrdOrderStatusCode> orderStautsCodeList = dao.findForList(getSqlName("getCodesByType1"), pd, OrdOrderStatusCode.class);
        if (!CollectionUtils.isEmpty(orderStautsCodeList)) {

            Map<String, List<OrderStatusCodeDto>> codeDtoMap = this.getCodeDtoMap(orderStautsCodeList);

            List<SysDict> codeOpertTypeList = sysDictService.findByCatalog(CommCodes.SYS_DICT_ORD_STATUS_CODE_OPERTYPE);
            for (SysDict operType : codeOpertTypeList) {
                TrackStatusOperTypeDto dto = new TrackStatusOperTypeDto();
                dto.setOperType(operType.getCode() + "_1");
                dto.setOperTypeName(operType.getName() + "正常");
                dto.setCodeDtoList(codeDtoMap.get(dto.getOperType()));
                operTypeDtoList.add(dto);

                TrackStatusOperTypeDto operTypeDtoEx = new TrackStatusOperTypeDto();
                operTypeDtoEx.setOperType(operType.getCode() + "_2");
                operTypeDtoEx.setOperTypeName(operType.getName() + "异常");
                operTypeDtoEx.setCodeDtoList(codeDtoMap.get(operTypeDtoEx.getOperType()));
                operTypeDtoList.add(operTypeDtoEx);
            }
        }
        return operTypeDtoList;
    }

    private Map<String, List<OrderStatusCodeDto>> getCodeDtoMap(List<OrdOrderStatusCode> orderStautsCodeList) {
        Map<String, List<OrderStatusCodeDto>> codeDtoMap = Maps.newHashMap();
        for (OrdOrderStatusCode statusCode : orderStautsCodeList) {
            //组装OrderStatusCodeDto
            OrderStatusCodeDto orderStatusCodeDto = new OrderStatusCodeDto();
            orderStatusCodeDto.setCode(statusCode.getCode());
            String messageTemplate = statusCode.getMessageTemplate();
            List<String> paramList = EntityUtils.extractMessageByRegular(messageTemplate, CommCodes.ORD_TRACKING_REGEX);
            orderStatusCodeDto.setParams(paramList);
            orderStatusCodeDto.setMessageTemplate(messageTemplate);
            //将其放入map
            String statusCodeKey = statusCode.getOperType() + "_" + statusCode.getType();
            if (codeDtoMap.get(statusCodeKey) == null) {
                List<OrderStatusCodeDto> statusCodeList = Lists.newArrayList();
                codeDtoMap.put(statusCodeKey, statusCodeList);
            }
            codeDtoMap.get(statusCodeKey).add(orderStatusCodeDto);
        }
        return codeDtoMap;
    }


    @Override
    public String[] getParams(String message) {
        Pattern pattern = Pattern.compile(REGEX);
        Matcher m = pattern.matcher(message);
        String[] results = new String[5];
        int i = 0;
        while (m.find()) {
            String result = m.group();
            results[i] = result;
            i++;
        }
        String[] strs = new String[i];
        for (int k = 0; k < i; k++) {
            strs[k] = results[k].replace("[", "").replace("]", "").trim();
        }
        return strs;
    }



    @Override
    public String getMaxCode(String startCode, int operType, int type) {

        ParamData pd = new ParamData();
        pd.put("startCode", startCode);
        pd.put("operType", operType);
        pd.put("type", type);
        String maxCode = (String) dao.findForObject(getSqlName("getMaxCodeByStartCode"), pd);
        return maxCode;
    }


    @Override
    public List<Integer> getRanks() {

        List<Integer> rankList = new ArrayList<>();
        rankList.add(OrderConstants.OrderTrackRank.TRACKING_CUSTOMER);//1
        if (!PrincipalUtils.isRoot()) {
            for (String permission : PrincipalUtils.getPermissions()) {
                if (permission.contains("ord-tracking-normal:hidden")) {
                    rankList.add(OrderConstants.OrderTrackRank.TRACKING_CUSTOMER_SERVICE);//2
                } else if (permission.contains("ord-tracking-abnormal:hidden")) {
                    rankList.add(OrderConstants.OrderTrackRank.TRACKING_MANAGER);//3 管理=销售，管理
                }
            }
        } else {
            rankList.add(OrderConstants.OrderTrackRank.TRACKING_CUSTOMER_SERVICE);
            rankList.add(OrderConstants.OrderTrackRank.TRACKING_MANAGER);
        }
        return rankList;
    }





}
